<!--长期工添加/修改页面-->
<template>
  <div class="app-container termWorkerAdd">
    <FixedBar>
      <template v-if="id !=null">
        <el-button  @click="handleLog(form.idCard)">入职流水</el-button>
        <el-button  @click="handleModifyLog(form.id)">变动记录</el-button>
      </template>

      <el-button type="primary" @click="onSubmit" v-if="disable !== '0'">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
    </FixedBar>
    <el-form :model="form" :rules="rules" ref="form" class="scheme-addForm" label-position="right" label-width="90px" :disabled="disable === '0'">

<!--      <div  style="text-align: left" >-->
<!--        <el-button  @click="handleLog(form.idCard)">入职流水</el-button>-->
<!--        <el-button  @click="handleModifyLog(form.id)">修改流水</el-button>-->
<!--      </div>-->
      <el-card class="mt20 box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
        </div>
        <div class="basicWrap">
          <div class="leftBox">
            <el-row :gutter="10">
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="姓名" prop="workerName">
                  <el-input v-model="form.workerName" placeholder="请输入姓名"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="身份证" prop="idCard">
                  <el-input v-model.trim="form.idCard" placeholder="请输入身份证号码" @change="optIdCard"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="性别" prop="sex">
                  <el-select v-model="form.sex" placeholder="" disabled>
                    <el-option
                      v-for="dict in sexOptions"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model="form.age" placeholder="" disabled/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="出生日期" prop="birthday" disabled>
                  <el-input v-model="form.birthday" placeholder="" disabled/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="联系电话" prop="phoneCode">
                  <el-input v-model.trim="form.phoneCode" placeholder="请输入联系电话"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="民族" prop="nation">
                  <el-input v-model="form.nation" placeholder="请输入民族"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="学历" prop="education">
                  <el-input v-model="form.education" placeholder="请输入学历"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="家庭住址" prop="homeAddress">
                  <el-input v-model="form.homeAddress" placeholder="请输入家庭住址"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="紧急联系人" prop="emergencyContact">
                  <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="紧急电话" prop="emergencyContactPhone">
                  <el-input v-model.trim="form.emergencyContactPhone" placeholder="请输入紧急联系人电话"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="招聘渠道" prop="companyName">
                  <el-input v-model="form.companyName" placeholder="请输入招聘渠道"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="推荐人" prop="recommender">
                  <el-input v-model="form.recommender" placeholder="请输入推荐人"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="银行卡" prop="bankCardNumber">
                  <el-input v-model.trim="form.bankCardNumber" placeholder="请输入银行卡号码"/>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12" :lg="8">
                <el-form-item label="开户行" prop="bankAddress">
                  <el-input v-model="form.bankAddress" placeholder="请输入开户行"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="rightBox">
            <el-upload
              class="avatar-uploader"
              accept=".jpg"
              :headers="uploadImg.headers"
              :action="uploadImg.url"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">

              <div slot="tip" class="el-upload__tip">支持jpg格式，240*320</div>
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

        </div>

      </el-card>



      <el-card class="mt20 box-card" >
        <div slot="header" class="clearfix">
          <span>岗位信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="员工状态" prop="workStatus">
              <el-select v-model="form.workStatus" placeholder="请选择">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="班组" prop="clazzId">
              <el-select v-model="form.clazzId" multiple placeholder="请选择">
                <el-option
                  v-for="dict in clazzOptions"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="区域" prop="areaId">
              <el-select
                v-model="form.areaId"
                placeholder="请选择"
                clearable
                size="small"

              >
                <el-option
                  v-for="dict in areaOptions"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="组别" prop="groupId">
              <el-select
                v-model="form.groupId"
                placeholder="组别"
                clearable
                size="small"

              >
                <el-option
                  v-for="dict in groupOptions"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="岗位" prop="postId">
              <el-select
                v-model="form.postId"
                placeholder="请选择"
                clearable
                size="small"

              >
                <el-option
                  v-for="dict in postOptions"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="入职时间" prop="comeTime">
              <el-date-picker clearable size="small" style="width: 100%"
                              v-model="form.comeTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择入职时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="试用期系数" prop="probationRate">
              <el-input-number :min="0" :max="1" :precision="2" style="width: 100%"
                               v-model="form.probationRate" :controls="false"
                               placeholder="请填入系数">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="离职时间" prop="leaveTime">
              <el-date-picker clearable size="small" style="width: 100%"
                              v-model="form.leaveTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择离职时间">
              </el-date-picker>
            </el-form-item>

          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="职级" prop="professionId">
              <el-select
                v-model="form.professionId"
                placeholder="请选择"
                clearable
                size="small"

              >
                <el-option
                  v-for="dict in professionOptions"
                  :key="dict.key"
                  :label="dict.value"
                  :value="dict.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="转正时间" prop="regularTime">
              <el-date-picker clearable size="small" style="width: 100%"
                              v-model="form.regularTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择转正时间">
              </el-date-picker>
            </el-form-item>
            </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
<!--            <el-form-item label="薪资方式" prop="salaryMethod">-->
<!--              <el-select-->
<!--                v-model="form.salaryMethod"-->
<!--                placeholder="请选择"-->
<!--                clearable-->
<!--                size="small"-->
<!--              ><el-option-->
<!--                v-for="dict in salaryMethodOptions"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
              </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="在职阶段" prop="jobStatus">
              <el-select
                v-model="form.jobStatus"
                placeholder="请选择"
                clearable
                size="small"
              ><el-option
                  v-for="dict in jobStatusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
                </el-col>
<!--          <el-col :xs="24" :sm="12" :md="8" :lg="6">-->
<!--            <el-form-item label="全勤奖" prop="fullBonus">-->
<!--              <el-input v-model="form.fullBonus" placeholder="请输入全勤奖" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item label="黑名单" prop="status">

            <el-select
              v-model="form.status"
              placeholder="请选择"
              clearable
              size="small"
            ><el-option
              v-for="dict in blacklistOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>
      </el-card>



    </el-form>

    <!--上传头像-->
    <el-dialog :title="uploadImg.title" :visible.sync="uploadImg.open" width="400px" append-to-body>
      <el-upload
        ref="uploadImg"
        :multiple="true"
        :limit="1"
        accept=".jpg,.png"
        :headers="uploadImg.headers"
        :action="uploadImg.url"
        :disabled="uploadImg.isUploading"
        :on-progress="handleImgUploadProgress"
        :on-success="handleImgSuccess"
        :on-change="beforeUpload"
        :auto-upload="false"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div>仅允许导入<span class="red">.jpg,.png</span>的图片格式文件</div>
          <div>图片像素接近<span class="red">300*300</span>,文件大小<span class="red">在500kb以下</span></div>
        </div>

      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImgForm">确 定</el-button>
        <el-button @click="uploadImg.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  getWorker,
  addWorker,
  updateWorker,uploadPic,listDept,listProfessionRank
} from "@/api/job/termWorker/termWorker";
import {isIdentityId, getSex, getAge, getBirth} from "@/api/validate";
import { getToken } from "@/utils/auth";
import FixedBar from '@/components/FixedBar';

export default {
  name: "addOrEdit_index",
  components:{
    FixedBar
  },
  data() {
    return {
      imageUrl:'', //头像
      id: this.$route.query.id,
      disable: this.$route.query.disable,
      form: {
        probationRate:0.80,
      },
      uploadImg: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "工具类导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,

        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url:process.env.VUE_APP_BASE_API + "/ploadPictureApi/addTermWorkerImg" // 上传的图片服务器地址
      },
      fileList:[],
      imgSrc:'',
      groupOptions: [],
      postOptions: [],
      clazzOptions: [],
      areaOptions: [],
      professionOptions: [],
      sexOptions: [{value: 1, label: '男'}, {value: 2, label: '女'}],
      statusOptions: [{value: 1, label: '在职'}, {value: 0, label: '离职'}],
      hmdOptions: [{value: 1, label: '是'}, {value: 0, label: '否'}, {value: -1, label: '请选择'}],
      jobStatusOptions:[{value: 0, label: '试岗期'},{value: 1, label: '试用期'}, {value: 2, label: '正式工'}],
      salaryMethodOptions:[{value: 0, label: '班次*单价 '}, {value: 1, label: ' 计件制'}],
      blacklistOptions: [{value: 1, label: '是'}, {value: 0, label: '否'}],
      rules: {
        workerName: [
          {required: true, message: "姓名不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '姓名长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        clazzId: [
          {required: true, message: "班组不能为空", trigger: "blur"},
        ],
        workStatus: [
          {required: true, message: "员工状态不能为空"}
        ],


        idCard: [
          {required: true, message: "身份证不能为空", trigger: "blur"}
        ],
        phoneCode: [
          {required: true, message: "联系方式不能为空", trigger: "blur"},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        nation: [
          {max: 10, message: '民族长度小于10', trigger: 'blur'}
        ],
        education: [
          {max: 10, message: '学历长度小于10', trigger: 'blur'}
        ],
        homeAddress: [
          {max: 200, message: '家庭地址长度小于200', trigger: 'blur'}
        ],
        companyName: [
          {max: 200, message: '招聘渠道长度小于200', trigger: 'blur'}
        ],
        emergencyContact: [
          {max: 25, message: '紧急联系人长度小于25', trigger: 'blur'}
        ],
        emergencyContactPhone: [
          {max: 200, message: '紧急联系人电话长度小于20', trigger: 'blur'},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        recommender: [
          {max: 10, message: '紧急联系人长度小于10', trigger: 'blur'}
        ],
        remark: [
          {max: 500, message: '推荐人长度小于500', trigger: 'blur'}
        ],
        bankCardNumber: [
          {max: 64, message: '银行卡长度小于500', trigger: 'blur'}
        ],
        bankAddress: [
          {max: 255, message: '开户行地址长度小于255', trigger: 'blur'}
        ],
        groupId: [{required: true, message: "组别不能为空", trigger: "blur"}],
        postId: [{required: true, message: "岗位不能为空", trigger: "blur"}],
      },
    }
  },
  created() {
    this.listDept();
    this.handleWorkerInfo();
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // console.log(res,file);
      if(res && res.code === 200){
        this.imageUrl = URL.createObjectURL(file.raw);
        this.form.imgUrl = res.url;
      }

    },
    beforeAvatarUpload(file) {
      // console.log(file);
      const allow = ['image/jpeg','image/png']
      const isAllow = allow.indexOf(file.type) > -1;
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isAllow) {
        this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isAllow && isLt2M;
    },
    /**
     * 长期工详情获取
     */
    handleWorkerInfo(){
      if (!this.id){
        return;
      }
      getWorker(this.id).then(response => {
        // console.log(response)
        if(response && response.code === 200){
          const data = response.data;
          if(data.imgUrl){  //处理图片
            this.imageUrl = data.imgUrl;
            this.form.imgUrl = data.imgUrl;
          }
        }
        this.form = response.data;
        if (null != response.data.clazzId && "" !== response.data.clazzId) {
          let clazzIdArray = response.data.clazzId.split(",");
          let clazzIdNumberArray = [];
          for (let i = 0; i < clazzIdArray.length; i++) {
            clazzIdNumberArray.push(Number(clazzIdArray[i]));
          }
          this.form.clazzId = clazzIdNumberArray;
        } else {
          this.form.clazzId = [];
        }

        if (response.data.imgUrl == null || response.data.imgUrl === '') {
          this.imgSrc = '/images/upload/xtimg/zwt.png';
        } else {
          this.imgSrc = response.data.imgUrl;
        }
        this.$forceUpdate();
      });
    },

    /**
     * 提交按钮
     */
    onSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
         let result =this.optIdCard(this.form.idCard);
         if(result==-1){
           return ;
         }
            // if (this.form.salaryMethod == 1 && this.form.fullBonus !=null) {
            //   if (this.form.professionId == null) {
            //     this.$alert("工资计件制无职级员工不能有全勤奖，请核对", "提示", {dangerouslyUseHTMLString: true});
            //     return;
            //   }
            // }

            // if(this.form.fullBonus !=null){
            //
            //   var reg=/^(0|([1-9]\d*))$/;
            //    if(!reg.test(this.form.fullBonus)){
            //      this.$alert("全勤奖为大于零的正整数，请核对", "提示", {dangerouslyUseHTMLString: true});
            //      return;
            //    }
            // }

          let clazzId = this.form.clazzId;
          this.form.uplaodImgFlag=this.imageUrl ? 1 : 0;
          const params = {...this.form,clazzId:clazzId.join(",")};
          // console.log(params)

          //处理请求
          this.loading = true;
          if (params.id) {
            this.handleUpdate(params);
          } else {
            this.handleAdd(params);
          }
        }
      })
    },

    /**
     * 处理添加请求
     */
    handleAdd(params) {
      addWorker(params).then(response => {
        this.msgSuccess("新增成功");
        this.loading = false;
        this.onCancel();
      });
    },

    /**
     * 处理修改请求
     */
    handleUpdate(params) {
      updateWorker(params).then(response => {
        this.msgSuccess("修改成功");
        this.loading = false;
        this.onCancel();
      });
    },

    /**
     * 取消按钮
     */
    onCancel() {
      this.$router.replace({path: "/basic/personnel/termWorker"});
    },

    optIdCard(value) {
      let errorMsg = isIdentityId(value);
      if (errorMsg != '') {
        this.$alert(errorMsg, "提示", {dangerouslyUseHTMLString: true});
        return -1;
      } else {
        let age = getAge(value);

        // if (Number(age) > 50 || Number(age) < 20) {
        //   this.$alert("年龄要求在20-50之间，请核对", "提示", {dangerouslyUseHTMLString: true});
        //   return -1;
        // }
        let sex = getSex(value);
        let birth = getBirth(value);

        this.form.birthday = birth;
        this.form.age = age;
        this.form.sex = sex;
        this.$forceUpdate();
      }
    },

    /**
     * 处理图片
     */
    handleImg() {
      this.uploadImg.title = "上传照片";
      this.uploadImg.open = true;
      this.uploadImg.url= "/ploadPictureApi/addTermWorkerImg";
    },

    /**
     * 提交相片
     */
    submitImgForm() {
      uploadPic(this.uploadImg.url,this.fileList).then(res => {
        this.fileList = [];
        this.uploadImg.open = false;
        this.uploadImg.isUploading = false;
        this.$refs.uploadImg.clearFiles();
        this.uplaodImgFlag =1;
        console.log("=======================***"+this.uplaodImgFlag);
        this.form.imgUrl = res.url;
      });
    },
    // 图片上传中处理
    handleImgUploadProgress(event, file, fileList) {
      this.uploadImg.isUploading = true;
    },
    // 图片上传成功处理
    handleImgSuccess(response, file, fileList) {
      this.uploadImg.open = false;
      this.uploadImg.isUploading = false;
      this.$refs.uploadImg.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
    },
    //上传之前
    beforeUpload(file,fileList) {
      // 1、判断文件名是否重复，不允许上传相同文件
      let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
      if(existFile){
        fileList.pop()
      }
      this.fileList = fileList;
    },
    listDept() {
      listDept().then(
        response => {
          this.groupOptions = response.data.group;
          this.postOptions = response.data.post;
          this.areaOptions = response.data.area;
          this.clazzOptions = response.data.clazz;
        });
      listProfessionRank().then(
        response => {
          this.professionOptions = response.data;
        });
    },

    handleLog(idCard) {
      this.$router.push({path:"/basic/personnel/log",query:{idCard:idCard}});
    },

    handleModifyLog(id) {
      this.$router.push({path:"/basic/personnel/modifyLog",query:{id:id}});
    },




  },
}
</script>

<style scoped>
/*.el-input{*/
/*  width: 80%;*/
/*}*/
/*.el-input-number{*/
/*  width: 80%;*/
/*}*/
/*.el-select{*/
/*  width: 80%;*/
/*}*/
.red{
  color: red;
}
  .basicWrap{
    display: flex;
  }
  .basicWrap .leftBox{
    flex: 1;
  }
  .basicWrap .rightBox{
    width: 130px;
    margin-left:40px;
    text-align: center;
  }


</style>
<style>
  .termWorkerAdd .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .termWorkerAdd .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .termWorkerAdd .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }
  .termWorkerAdd .avatar {
    width: 120px;
    height: 160px;
    display: block;
  }

  .termWorkerAdd .el-input-number.is-without-controls .el-input__inner{
    text-align: left;
  }
</style>
